<template>
  <div class="ease-sku-table">
    <el-table
      border
      size="mini"
      :data="lists"
      v-if="lists.length"
      :span-method="handleSpanMethod"
    >
      <template v-for="(label, index) in columns">
        <!-- 为什么要判断label: 动态添加规格名的时候规格名不为undefiend时未动态显示, 没有看table-column实现暂时这么解决  -->
        <el-table-column
          v-if="label"
          :label="label"
          align="center"
          :key="index"
        >
          <template slot-scope="scope">
            {{ scope.row.skuProps[index] && scope.row.skuProps[index].v }}
          </template>
        </el-table-column>
      </template>
      <el-table-column prop="price" label="是否启用" align="center" width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" size="mini"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="规格编码" align="center" width="160">
        <template slot-scope="scope">
          <el-input
            :disabled="!scope.row.enable"
            v-model="scope.row.skuCode"
            size="mini"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="markedPrice"
        label="成本价"
        width="160"
        align="center"
      >
        <template slot-scope="scope">
          <el-input-number
            :disabled="!scope.row.enable"
            :precision="2"
            :min="0"
            controls-position="right"
            v-model="scope.row.costPrice"
            size="mini"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="销售价格" align="center" width="160">
        <template slot-scope="scope">
          <el-input-number
            :disabled="!scope.row.enable"
            :precision="2"
            :min="0"
            controls-position="right"
            v-model="scope.row.retailPrice"
            size="mini"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="赏金" align="center" width="160">
        <template slot-scope="scope">
          <el-input-number
            :disabled="!scope.row.enable"
            :precision="2"
            :min="0"
            controls-position="right"
            v-model="scope.row.rewardAmount"
            size="mini"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column prop="stockNum" label="库存" align="center" width="160">
        <template slot-scope="scope">
          <el-input-number
            :disabled="!scope.row.enable"
            :min="0"
            controls-position="right"
            v-model="scope.row.stockNum"
            size="mini"
          ></el-input-number>
        </template>
      </el-table-column>
      <!--      手机壳型号较多，需要单独设置-->
      <el-table-column
        v-if="itemCode === 'DIY_MOBILE_CASE'"
        prop="modelIds"
        label="适配型号"
        align="center"
        width="190"
      >
        <template slot-scope="scope">
          <el-cascader
            v-model="scope.row.brandModelIds"
            size="small"
            :disabled="!scope.row.enable"
            :show-all-levels="false"
            :options="brandModels"
            :props="{ multiple: true, children: 'models' }"
            collapse-tags
            clearable
          ></el-cascader>
        </template>
      </el-table-column>
      <el-table-column
        v-if="itemCode === 'DIY_MOBILE_CASE'"
        label="模具关联"
        align="center"
        width="190"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            :disabled="!scope.row.enable"
            @click="onBindMold(scope.row)"
            >绑定模具</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        v-if="itemCode === 'DIY_EAR_MUFF' || itemCode === 'DIY_TABLET_MUFF'"
        label="设置模板"
        align="center"
        width="190"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            :disabled="!scope.row.enable"
            @click="onSetEarMuffTemplate(scope.row)"
            >设置模板</el-button
          >
        </template>
      </el-table-column>
      <!--      手机壳型号较多，需要单独设置-->
      <!--      样本在爆款里面起预览作用，因为客户可以结合自己的型号来看效果图-->
      <el-table-column
        v-if="itemCode === 'COMMON'"
        prop="price"
        label="样本设置"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="warning"
            :disabled="!scope.row.enable"
            @click="onSetSample(scope.row)"
            >设置样本</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import Vue from "vue";
import { Table, TableColumn, InputNumber } from "element-ui";
import { flatten } from "../utils";
import { getBrandModelsTree } from "@/api/admin-api/BrandApi";

Vue.use(Table);
Vue.use(TableColumn);
Vue.use(InputNumber);

export default {
  name: "sku-table",

  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    itemCode: {
      type: String,
      defaultValue: "COMMON"
    },
    // 需要附加的字段
    flatten: {
      type: Array,
      default() {
        return [];
      }
    },
    // 自定义sku的id key
    optionValue: {
      type: String,
      default: "id"
    },
    // 自定义sku的text key
    optionText: {
      type: String,
      default: "text"
    }
  },

  data() {
    return {
      rowspan: [],
      lists: [],
      brandModels: []
    };
  },

  computed: {
    filter() {
      console.log("filter", this.data);
      return this.data.filter(item => item.text && item.leaf.length);
    },

    columns() {
      return this.filter.map(item => item[this.optionText]);
    }
  },

  watch: {
    filter: {
      deep: true,
      immediate: true,
      handler() {
        console.log("filter handler", this.filter);
        this.lists = flatten(this.filter, this.flatten);
        console.log("this.lists", this.lists);
        this.computeRowspan();
      }
    },

    lists: {
      deep: true,
      immediate: true,
      handler(data) {
        this.$emit("on-change-data", data);
      }
    }
  },
  mounted() {
    this.loadModelsTree();
  },
  methods: {
    onSetEarMuffTemplate(row) {
      //设置耳机套模板
      if (row.id) {
        const propStr = row.skuProps.map(item => item.v).join("-");
        if (this.itemCode === "DIY_EAR_MUFF") {
          this.$router.push(
            "/diy/ear_muff/sku_templates?sku_id=" +
              row.id +
              "&sku_name=" +
              propStr
          );
        }
        if (this.itemCode === "DIY_TABLET_MUFF") {
          this.$router.push(
            "/diy/tablet_muff/sku_templates?sku_id=" +
              row.id +
              "&sku_name=" +
              propStr
          );
        }
      } else {
        this.$message.error("请先点击下方保存按钮后再设置模板哦");
      }
    },
    onBindMold(row) {
      if (row.id) {
        const propStr = row.skuProps.map(item => item.v).join("-");
        this.$router.push(
          "/diy/mb_case/bind_mold?sku_id=" + row.id + "&sku_name=" + propStr
        );
      } else {
        this.$message.error("请先点击下方保存按钮后再绑定模具哦");
      }
    },
    onSetSample(row) {
      if (row.id) {
        const propStr = row.skuProps.map(item => item.v).join("-");
        console.log("propStr", propStr);
        this.$router.push(
          "/shop/sku_sample?item_id=" +
            row.itemId +
            "&sku_id=" +
            row.id +
            "&item_name=" +
            this.$route.query.name +
            "&sku_name=" +
            propStr
        );
      } else {
        this.$message.error("请先点击下方保存按钮后再设置样本");
      }
      console.log(row);
    },
    computeRowspan() {
      this.rowspan = [];
      const rowspan = index => {
        let span = [];
        let dot = 0;

        this.lists.map((item, idx) => {
          if (idx === 0) {
            span.push(1);
          } else {
            if (
              item.skuProps[index].v === this.lists[idx - 1].skuProps[index].v
            ) {
              span[dot] += 1;
              span.push(0);
            } else {
              dot = idx;
              span.push(1);
            }
          }
        });

        this.rowspan.push(span);
      };

      this.filter.map((item, index) => {
        rowspan(index);
      });
    },
    loadModelsTree() {
      getBrandModelsTree().then(data => {
        console.log("modelsTree", data);
        this.brandModels = data;
      });
    },
    handleSpanMethod({ row, column, rowIndex, columnIndex }) {
      for (let i = 0; i < this.filter.length; i++) {
        if (columnIndex === i) {
          if (this.rowspan[i] && this.rowspan[i][rowIndex]) {
            return {
              rowspan: this.rowspan[i][rowIndex],
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }
    }
  }
};
</script>
